package com.kay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kay.mapper.TokenMapper;
import com.kay.mapper.UserMapper;
import com.kay.pojo.Token;
import com.kay.pojo.User;
import com.kay.service.CodeService;
import com.kay.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;

/**
 * @Description:
 * @Author: Kay
 * @CreateDate: 2021/9/18$ 12:32$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/9/18$ 12:32$
 */
@Service
public class UserServiceImpl implements UserService {

    @Reference
    private CodeService codeService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenMapper tokenMapper;

    /**
     * 注册接⼝
     *
     * @param email
     * @param password
     * @param code
     * @return true成功，false失败
     */
    @Override
    public int register(String email, String password, String code) {
        if (StringUtils.isAnyEmpty(email, password, code)) return -1;

        // 校验验证码  0正确 1错误 2超时
        if (codeService.validateCodeAndEmail(email, code) != 0) return 2;

        // 是否注册
        if (isRegistered(email)) return -1;

        // 新增用户信息
        User user = new User(email, password);
        int insert = userMapper.insert(user);

        return insert > 0 ? 0 : 3;
    }

    /**
     * 是否已注册, 根据邮箱判断,true代表已经注册过，false代表尚未注册
     *
     * @param email
     * @return
     */
    @Override
    public boolean isRegistered(String email) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("email", email);
        User user = userMapper.selectOne(wrapper);
        return user == null ? false : true;
    }

    /**
     * 登录接⼝
     * 1. 验证⽤户名密码合法性
     * 2. 根据⽤户名和密码⽣成token，token存⼊数据库，并写⼊cookie中
     * 3. 登陆成功返回token信息
     *
     * @param email
     * @param password
     * @return
     */
    @Override
    public String login(String email, String password) {
        if (StringUtils.isAnyEmpty(email, password)) return "false";

        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("email", email)
                .eq("password", password);
        User user = userMapper.selectOne(wrapper);
        // 验证⽤户名密码合法性
        if (user == null) return "false";

        // 此处⽣成⼀个UUID模拟即可
        String tokeS = UUID.randomUUID().toString();
        // token存⼊数据库， 登陆成功返回token信息
        return tokenMapper.insert(new Token(email, tokeS)) > 0 ? tokeS : "false";
    }


    /**
     * 根据token查询⽤户登录邮箱接⼝
     *
     * @param token
     * @return
     */
    @Override
    public String info(String token) {
        Token tokenRecord = tokenMapper.selectTopOneByToken(token); // todo token 有效期问题
        return tokenRecord == null ? "" : tokenRecord.getEmail();
    }
}
